package job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mo.star.common.ResultUtils;
import com.mo.star.mapper.UsertableMapper;
import com.mo.star.pojo.User;
import com.mo.star.service.impl.UsertableServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务
 */
@Log4j
@Component
public class PreCacheJob {
    @Resource
    private UsertableServiceImpl usertableService;
    @Resource
    private RedisTemplate redisTemplate;
    List<User> userList = new ArrayList<>();
    //每三天执行一遍
    @Scheduled(cron = "0 58 23 1/3 * ? ")
    public void doCacheJob(){
        String UserId="8c1f24dfa0a846d290b11cd74598aba1";
        //获得已登录用户信息
        User loginUser = userList.get(0);
        ValueOperations<String,Object> var = redisTemplate.opsForValue();
        //设置缓存键
        String redisKey = String.format("com:mo:star:recommend:%s",UserId);
        //获取缓存
        Page<User> userPage = (Page<User>) var.get(redisKey);
        if(userPage !=null)
            return;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //缓存为空则读数据库
        userPage=usertableService.page(new Page<>(20,1),queryWrapper);
        log.info("-------------定时缓存------------");
        try{
            //写缓存进redis
            var.set(redisKey,userPage,3, TimeUnit.DAYS);
        }catch (Exception e){
            log.error("redis set key error",e);
        }
    }

}
